package com.kasax.httpclient.interceptors;

import com.kasax.httpclient.beans.Response;
import com.kasax.httpclient.core.HttpCondec;
import com.kasax.httpclient.core.HttpConnection;
import com.kasax.httpclient.core.inters.Interceptor;
import com.kasax.httpclient.utils.LogUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

public class CallServerInterceptor implements Interceptor {

    @Override
    public Response intercpt(Chain chain) throws IOException {
        LogUtils.i(getClass(), "intercpt");
        HttpCondec httpCondec = chain.httpCodec();
        HttpConnection connection = chain.connection();
        // TODO: 2024-09-28 这里为空了
        InputStream inputStream = connection.call(httpCondec);
        //HTTP/1.1 200 OK 空格隔开的响应状态
        String readLine = httpCondec.readLine(inputStream);

        Map<String, String> headers = httpCondec.readHeaders(inputStream);
        // 是否保持连接
        boolean isKeepAlive = false;
        if (headers.containsKey(HttpCondec.HEAD_CONNECTION)) {
            isKeepAlive = headers.get(HttpCondec.HEAD_CONNECTION).equalsIgnoreCase(HttpCondec.HEAD_VALUE_KEEP_ALIVE);
        }
        int contentLength = -1;
        if (headers.containsKey(HttpCondec.HEAD_CONTENT_LENGTH)) {
            contentLength = Integer.valueOf(headers.get(HttpCondec.HEAD_CONTENT_LENGTH));
        }
        // 分块编码数据
        boolean isChuncked = false;
        if (headers.containsKey(HttpCondec.HEAD_TRANSFER_ENCODING)) {
            isChuncked = headers.get(HttpCondec.HEAD_TRANSFER_ENCODING).equalsIgnoreCase(HttpCondec.HEAD_VALUE_CHUNKED);
        }
        String body = null;
        if (contentLength > 0) {
            byte[] bytes = httpCondec.readBytes(inputStream, contentLength);
            body = new String(bytes);
        } else if (isChuncked) {
            body = httpCondec.readChunked(inputStream);
        }
        String[] split = readLine.split(" ");
        connection.updateLastUseTime();
        return new Response(Integer.valueOf(split[1]), contentLength, headers, body, isKeepAlive);
    }
}
